/*
 * 使用UDP协议
 * 连接url分发server，以获取url
 * */
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include "dist_url_comm.h"

/*
 * 获取URL列表，在返回的char *内存中，每行一个url(\n区分)
 * ip		:dist_url server的ip地址;
 * port		:dist_url server的端口;
 * timeout	:获取超时时间，单位为秒, 暂时未启用
 * num		:要获取的url的数量
 * regular	:获取到的url为匹配到regular的url，regular参数为正则表达式，采用Perl形式正则表达式
 * return	:返回URL集合，每行一个url(\n区分行)
 * */
char *get_urls(const struct in_addr *ip, unsigned short port, unsigned timeout, int num, const char *regular)
{
	int sockfd;
	struct sockaddr_in servaddr;
	DIST_URL_PROTO_CLIENT c;
	if (init_struct_client(&c, num, regular) < 0)
		return NULL;

	bzero(&servaddr, sizeof servaddr);
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	memcpy(&servaddr.sin_addr, ip, sizeof(servaddr.sin_addr));

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd == -1) {
		//loggggggggggggggg
		return NULL;
	}
	char *request = struct2str_client(&c);
	if (sendto(sockfd, request, strlen(request), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
		free(request);
		close(sockfd);
		//loggggggggggggggg
		return NULL;
	}
	free(request);
	char buf[8192];
	DIST_URL_PROTO_SERVER *s = NULL, *s_array = NULL;
	int parse_ret, recv_len;
	char *ret = NULL;
	DIST_URL_SERVER_HANDLE sh;
	memset(&sh, 0, sizeof sh);
	while (1) {
		recv_len = recvfrom(sockfd, buf, sizeof buf, 0, NULL, NULL);
		if (recv_len < 0) {
			close(sockfd);
			//logggggggggggggg
			return NULL;
		}
		buf[recv_len] = '\0';
		parse_ret = str2struct_server(&s, buf);
		if (parse_ret == -1) {
			//logggggggggggggggg
			destroy_server_handle(&sh);
			close(sockfd);
			return NULL;
		}
		if (add_s_pack(&sh, s) == 1) {	//收包完毕
			ret = sh.full_data;
			sh.full_data = NULL;
			destroy_server_handle(&sh);
			break;
		}
	}
	close(sockfd);
	return ret;
}
